package com.tancire.net.utils;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

@Component
public class OpenidUtils {

    // 算法名。
    private static final String KEY_NAME = "AES";
    // 加解密算法/模式/填充方式。
    // ECB模式只用密钥即可对数据进行加密解密，CBC模式需要添加一个iv。
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

    private static final Integer INVALID_ACCESS_TOEKN = 40001;

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    public String getOpenid(String code) {
        BufferedReader in = null;
        // appid和secret是开发者分别是小程序ID和小程序密钥，开发者通过微信公众平台-》设置-》开发设置就可以直接获取，
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            URL weChatUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = weChatUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            try {
                return JSONObject.parseObject(sb.toString()).getString("openid");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sb.toString();
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    /**
     * 获取 access_token
     *
     * @return
     */
    public String getAccessToken() {
        BufferedReader in = null;
        // appid和secret是开发者分别是小程序ID和小程序密钥，开发者通过微信公众平台-》设置-》开发设置就可以直接获取，
        // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        try {
            URL weChatUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = weChatUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            try {
                return JSONObject.parseObject(sb.toString()).getString("access_token");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sb.toString();
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public String getWxUserPhone(String code, String accessToken) {
        BufferedReader in = null;
        // appid和secret是开发者分别是小程序ID和小程序密钥，开发者通过微信公众平台-》设置-》开发设置就可以直接获取，
        // https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken + "&code=" + code;
        try {
            URL weChatUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = weChatUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            try {
                JSONObject jsonObject = JSONObject.parseObject(sb.toString());
                JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
                String purePhoneNumber = phoneInfo.getString("purePhoneNumber");
                return purePhoneNumber;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sb.toString();
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    /**
     * 解密方法。
     *
     * @param encryptedData
     * @param sessionKey
     * @param iv
     * @return
     */
    /*public String decrypt(String encryptedData, String sessionKey, String iv) {

        byte[] dataByte = Base64.decode(encryptedData.getBytes(StandardCharsets.UTF_8));
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey.getBytes(StandardCharsets.UTF_8));
        // 偏移量
        byte[] ivByte = Base64.decode(iv.getBytes(StandardCharsets.UTF_8));

        try {
            // 如果密钥不足16位，那么就补足，这个if 中的内容很重要。
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + 1;
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            SecretKeySpec spec = new SecretKeySpec(keyByte, KEY_NAME);
            AlgorithmParameters parameters = AlgorithmParameters.getInstance(KEY_NAME);
            parameters.init(new IvParameterSpec(ivByte));
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return result;
            }
        } catch (Exception e) {
            // logger.error("cipher error: {}, {}, {}", encryptedData, sessionKey, iv, e);
        }
        return null;
    }*/
    /*public static void main(String[] args) {
        String a = "{\"session_key\":\"Rnayx3M8c+QCmvbPulvk4Q==\",\"openid\":\"olDfu5X6iYpGFB1YS_BlbHItapZc\"}";
        System.out.println(JSONObject.parseObject(a).getString("openid"));
    }*/

}
